package com.hm.system.aspect;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.hm.common.model.LoginUserInfo;
import com.hm.common.util.CommonDef;
import com.hm.system.auto.SystemProperties;

/**
 * @author shishun.wang
 * @date 下午2:44:33 2016年8月22日
 * @version 1.0
 * @describe
 */
@Aspect
@Component
public class ActionAspectHandler {

	@Autowired
	private SystemProperties systemProperties;
	
//	@Autowired
//	private RequestRecordHandler requestRecordHandler;

	@Around("execution(* com.hm.system.web.**Controller.*(..))")
	public Object process(ProceedingJoinPoint point) throws Throwable{
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

		String uri = request.getRequestURI();
		if (!systemProperties.getSkipFilterValidate().contains(uri)) {
			HttpSession httpSession = request.getSession();
			if(null != httpSession){
				Object obj = request.getSession().getAttribute(CommonDef.BaseInit.SessionOrCookieToken.SESSION_LOGIN_USER_INFO);
				if(null != obj){
					
					if(systemProperties.getLogConfig().isReq()){
						//用户操作记录
//					MethodSignature signature = (MethodSignature) point.getSignature();
//					requestRecordHandler.handler(request, request.getm);// 记录用户操作日志
						
						LoginUserInfo userInfo = (LoginUserInfo) request.getSession()
								.getAttribute(CommonDef.BaseInit.SessionOrCookieToken.SESSION_LOGIN_USER_INFO);
						
						System.out.println(userInfo);
					}
				}else{
					sendError(CommonDef.ResponseState.REQUEST_TOKEN_LOSE, response);
					return null;
				}
			}else{
				sendError(CommonDef.ResponseState.REQUEST_TOKEN_LOSE, response);
				return null;
			}
		}
		return point.proceed();
	}
	
	public void sendError(int state,HttpServletResponse response){
		try {
			response.setCharacterEncoding("UTF-8");
			response.setStatus(state);
			JSONObject item = new JSONObject();
			{
				item.put("result", "会话超时,请重新登陆");
				item.put("message", "null");
			}
			response.getWriter().println(item.toJSONString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
